<script setup>
import { useAppStore, useWMSStore } from '@/stores'
import * as monaco from 'monaco-editor'
import proj4 from 'proj4'
import Map from 'ol/Map'
import View from 'ol/View'
import TileLayer from 'ol/layer/Tile'
import TileWMS from 'ol/source/TileWMS'
import Projection from 'ol/proj/Projection'

const appStore = useAppStore()
const wmsStore = useWMSStore()
const windowWidth = ref(window.innerWidth)
const windowHeight = ref(window.innerHeight)

const adaptHeight = appStore.showTabs ? (appStore.showFooter ? ref(187) : ref(227)) : appStore.showFooter ? ref(227) : ref(272)

const computedHeight = computed(() => windowHeight.value - adaptHeight.value)
let editor = null
const code = ref(`
window.olMap_wms = new Map({
  target: document.getElementById('olMap_wms'),
  view: new View({
    projection: 'EPSG:3857',
    multiWorld: true
  })
})
const tileLayer = new TileLayer({
  source: new TileWMS({
    url: 'https://iserver.supermap.io/iserver/services/map-china400/wms111/China',
    params: {
      LAYERS: 'China',
      FORMAT: 'image/png',
      VERSION: '1.1.1'
    }
  })
})
olMap_wms.addLayer(tileLayer)
olMap_wms.getView().fit([-2.0037508342789248e7, -2.003750834278914e7, 2.0037508342789244e7, 2.0037508342789087e7])
`)

const resetCode = () => {
  const model = editor.getModel()
  model.setValue(wmsStore.openlayersAddCode)
  setTimeout(() => editor.getAction('editor.action.formatDocument').run(), 800)
}

const runCode = () => {
  if (window.olMap_wms) {
    window.olMap_wms.setTarget(null)
    window.olMap_wms = null
  }
  editor.getAction('editor.action.formatDocument').run()
  try {
    eval(toRaw(editor).getValue())
  } catch (error) {
    window.$message.error(extractKeyInfo(error))
  }
}

function extractKeyInfo(message) {
  const match = JSON.stringify(message).match(/^(?:Error: )(.+?)\./)
  return match ? match[1] : 'No error info found'
}

const handleResize = () => {
  windowWidth.value = window.innerWidth
  windowHeight.value = window.innerHeight
}

function initMap() {
  proj4.defs('EPSG:3857', '+proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null +wktext +no_defs +type=crs')
  window.olMap_wms = new Map({
    target: document.getElementById('olMap_wms'),
    view: new View({
      projection: new Projection({
        code: 'EPSG:3857',
        extent: [-20037508.342789244, -20037508.342789244, 20037508.342789244, 20037508.342789244],
        units: 'm',
        global: true
      }),
      multiWorld: true
    })
  })
  const tileLayer = new TileLayer({
    source: new TileWMS({
      url: 'https://iserver.supermap.io/iserver/services/map-china400/wms111/China',
      params: {
        LAYERS: 'China',
        FORMAT: 'image/png',
        VERSION: '1.1.1'
      }
    })
  })
  olMap_wms.addLayer(tileLayer)
  olMap_wms.getView().fit([-2.0037508342789248e7, -2.003750834278914e7, 2.0037508342789244e7, 2.0037508342789087e7])
}

onMounted(() => {
  if (window.olMap_wms) {
    window.olMap_wms.setTarget(null)
    window.olMap_wms = null
    initMap()
  }
  window.addEventListener('resize', handleResize)
  editor = monaco.editor.create(document.getElementById('editorContainer'), {
    value: code.value, // 编辑器初始显示文字
    language: 'javascript', // 语言支持自行查阅demo
    automaticLayout: true, // 自适应布局
    // theme: 'vs-dark', // 官方自带三种主题vs, hc-black, or vs-dark
    foldingStrategy: 'indentation', // 代码可分小段折叠
    renderLineHighlight: 'all', // 行亮
    selectOnLineNumbers: true, // 显示行号
    minimap: {
      enabled: false
    },
    readOnly: false, // 只读
    fontSize: 14, // 字体大小
    scrollBeyondLastLine: false, // 取消代码后面一大段空白
    overviewRulerBorder: false, // 不要滚动条的边框
    wordWrap: 'on', // 自动换行
    tabSize: 2 // tab 缩进长度
  })
  editor.getAction('editor.action.formatDocument').run()
})

onUnmounted(() => window.removeEventListener('resize', handleResize))

watch(
  () => wmsStore.openlayersAddCode,
  () => {
    const model = editor.getModel()
    model.setValue(wmsStore.openlayersAddCode)
    setTimeout(() => editor.getAction('editor.action.formatDocument').run(), 800)
  }
)
watch(
  () => appStore.colorMode,
  () => (appStore.colorMode === 'light' ? monaco.editor.setTheme('vs') : monaco.editor.setTheme('vs-dark')),
  { immediate: true }
)
watch(
  () => appStore.showTabs,
  () => (appStore.showTabs ? (adaptHeight.value += 45) : (adaptHeight.value -= 45)),
  { immediate: true }
)
watch(
  () => appStore.showFooter,
  () => (appStore.showFooter ? (adaptHeight.value += 40) : (adaptHeight.value -= 40)),
  { immediate: true }
)
</script>

<template>
  <n-card title="加载代码">
    <template #header-extra>
      <n-button type="primary" quaternary @click="resetCode">
        <template #icon>
          <icon-park-outline-refresh />
        </template>
        重置
      </n-button>
      <n-button type="primary" quaternary @click="runCode">
        <template #icon>
          <icon-park-outline-link-cloud />
        </template>
        运行
      </n-button>
    </template>
    <n-infinite-scroll>
      <div id="editorContainer" :style="{ height: `${computedHeight}px` }"></div>
    </n-infinite-scroll>
  </n-card>
</template>
